﻿import 'dart:developer' as developer;
import 'package:getx_scaffold/getx_scaffold.dart';
import '../../../core/controllers/ring_controller.dart';
import '../../../services/ring_service.dart';
import '../../../services/device_sn_manager.dart';
import '../../../core/repository/default_api.dart';
import '../../../core/models/activity_data.dart';

/// 时间范围枚举
enum TimeRange { day, week, month }

/// 活动页面控制器
class ActivityLogic extends GetxController {
  static const String _tag = 'ActivityController';

  // 依赖注入的服务
  late RingController _ringController;
  late RingService _ringService;

  // 响应式状态变量
  final Rx<TimeRange> _currentTimeRange = TimeRange.day.obs;
  final RxInt _selectedTimeIndex = (-1).obs; // -1表示显示总计
  final Rxn<double> _dragLineX = Rxn<double>();
  final RxInt _selectedDayIndex = 6.obs; // 6表示今天，0表示6天前
  final RxList<int> _detailedStepsData = <int>[].obs;
  final RxBool _isLoadingDetailedData = false.obs;

  // API数据
  final Rxn<CompareDistanceData> _compareDistanceData =
      Rxn<CompareDistanceData>();
  final RxList<DailyTargetData> _targetSituationData = <DailyTargetData>[].obs;
  final RxList<int> _eventInfoHourlySteps = <int>[].obs; // 活动信息的小时步数数据
  final RxInt _eventInfoTotalSteps = 0.obs; // 活动信息的总步数
  final RxInt _eventInfoValidTime = 0.obs; // 活动信息的有效时长
  final RxInt _eventInfoCalories = 0.obs; // 活动信息的卡路里
  final RxString _eventInfoDateStart = ''.obs; // 活动信息的开始日期
  final RxString _eventInfoDateEnd = ''.obs; // 活动信息的结束日期
  final RxString _eventInfoRecordDate = ''.obs; // 活动信息的记录日期
  final RxString _eventInfoWeekName = ''.obs; // 活动信息的星期名称

  // Getter方法
  TimeRange get currentTimeRange => _currentTimeRange.value;
  int get selectedTimeIndex => _selectedTimeIndex.value;
  double? get dragLineX => _dragLineX.value;
  int get selectedDayIndex => _selectedDayIndex.value;
  List<int> get detailedStepsData => _detailedStepsData;
  bool get isLoadingDetailedData => _isLoadingDetailedData.value;
  CompareDistanceData? get compareDistanceData => _compareDistanceData.value;
  List<DailyTargetData> get targetSituationData => _targetSituationData;
  List<int> get eventInfoHourlySteps => _eventInfoHourlySteps;
  int get eventInfoTotalSteps => _eventInfoTotalSteps.value;
  int get eventInfoValidTime => _eventInfoValidTime.value;
  int get eventInfoCalories => _eventInfoCalories.value;
  String get eventInfoDateStart => _eventInfoDateStart.value;
  String get eventInfoDateEnd => _eventInfoDateEnd.value;
  String get eventInfoRecordDate => _eventInfoRecordDate.value;
  String get eventInfoWeekName => _eventInfoWeekName.value;

  // 获取戒指控制器
  RingController get ringController => _ringController;

  // 获取戒指服务
  RingService get ringService => _ringService;

  @override
  void onInit() {
    super.onInit();
    _initializeServices();
    // 延迟获取详细数据，避免在构建阶段调用Toast
    Future.delayed(const Duration(milliseconds: 100), () {
      fetchDetailedDataAndSendToApi();
      _fetchActivityData();
    });
  }

  /// 初始化服务
  void _initializeServices() {
    try {
      _ringController = Get.find<RingController>();
      _ringService = Get.find<RingService>();
      developer.log('✅ 服务初始化成功', name: _tag);
    } catch (e) {
      developer.log('❌ 服务初始化失败: $e', name: _tag);
      rethrow;
    }
  }

  /// 设置时间范围
  void setTimeRange(TimeRange timeRange) {
    _currentTimeRange.value = timeRange;
    developer.log('🕒 时间范围切换到: $timeRange', name: _tag);
    // 切换时间范围时重新获取数据
    _fetchActivityData();
  }

  /// 设置选中的时间段索引
  void setSelectedTimeIndex(int index) {
    _selectedTimeIndex.value = index;
  }

  /// 重置选中的时间段
  void resetSelectedTimeIndex() {
    _selectedTimeIndex.value = -1;
  }

  /// 设置拖动线位置
  void setDragLineX(double? x) {
    _dragLineX.value = x;
  }

  /// 设置选中的日期索引
  void setSelectedDayIndex(int index) {
    _selectedDayIndex.value = index;
    resetSelectedTimeIndex(); // 重置时段选择
    developer.log('📅 选中日期索引: $index', name: _tag);
  }

  /// 获取详细数据并发送到接口
  Future<void> fetchDetailedDataAndSendToApi() async {
    try {
      _isLoadingDetailedData.value = true;
      developer.log('📊 开始获取详细步数数据...', name: _tag);

      // 检查设备连接状态
      if (!_ringService.isConnected) {
        developer.log('❌ 设备未连接，无法获取详细数据', name: _tag);
        _showError('设备未连接，无法获取详细数据');
        return;
      }

      // 1. 获取今日的详细步数数据
      final success = await _ringService.queryStepsForDate('TODAY');
      if (!success) {
        developer.log('❌ 获取详细步数数据失败', name: _tag);
        _showError('获取详细步数数据失败');
        return;
      }

      // 等待数据接收
      await Future.delayed(const Duration(seconds: 2));
    } catch (e) {
      developer.log('❌ 获取详细数据异常: $e', name: _tag);
      _showError('获取详细数据异常: $e');
    } finally {
      _isLoadingDetailedData.value = false;
    }
  }

  /// 刷新详细数据
  Future<void> refreshDetailedData() async {
    await fetchDetailedDataAndSendToApi();
  }

  /// 获取活动页面所需的所有数据
  Future<void> _fetchActivityData() async {
    try {
      developer.log('📊 开始获取活动页面数据...', name: _tag);

      // // 获取设备序列号
      // final deviceSn = _ringController.getCurrentDeviceSn();
      // if (deviceSn.isEmpty) {
      //   developer.log('❌ 设备未连接，无法获取活动数据', name: _tag);
      //   return;
      // }

      // 获取设备SN
      final deviceSnManager = Get.find<DeviceSnManager>();
      final deviceSn = deviceSnManager.getDeviceSn();

      if (deviceSn.isEmpty) {
        developer.log('⚠️ 设备SN为空，无法获取活动数据', name: _tag);
        return;
      }

      // 获取当前日期
      final now = DateTime.now();
      final recordDate =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      // 并行调用所有接口
      await Future.wait([
        _fetchEventInfo(deviceSn, recordDate),
        _fetchEventExerciseInfo(deviceSn, recordDate),
        _fetchCompareDistanceRate(deviceSn, recordDate),
        _fetchTargetSituation(deviceSn, recordDate),
        _fetchPhysicalActivityLevel(deviceSn, recordDate),
      ]);

      developer.log('✅ 活动页面数据获取完成', name: _tag);
    } catch (e) {
      developer.log('❌ 获取活动页面数据异常: $e', name: _tag);
    }
  }

  /// 获取当前时间范围对应的type值
  String _getTypeFromTimeRange() {
    switch (_currentTimeRange.value) {
      case TimeRange.day:
        return '1';
      case TimeRange.week:
        return '2';
      case TimeRange.month:
        return '3';
    }
  }

  /// 获取活动信息
  Future<void> _fetchEventInfo(String deviceSn, String recordDate) async {
    try {
      final response = await DefaultApi().queryEventInfoGet(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: _getTypeFromTimeRange(),
        isShowErrMsg: false,
        isShowLoading: false,
      );
      developer.log('✅ 活动信息获取成功: $response', name: _tag);

      // 解析数据
      if (response != null && response['data'] != null) {
        final data = response['data'];
        _eventInfoTotalSteps.value = data['steps'] ?? 0;
        _eventInfoValidTime.value = data['validTime'] ?? 0;
        _eventInfoCalories.value = data['calories'] ?? 0;
        _eventInfoDateStart.value = data['dateStart'] ?? '';
        _eventInfoDateEnd.value = data['dateEnd'] ?? '';
        _eventInfoRecordDate.value = data['recordDate'] ?? '';
        _eventInfoWeekName.value = data['weekName'] ?? '';

        // 解析小时步数数据
        final List<dynamic>? eventInfoList = data['eventInfoVOList'];
        if (eventInfoList != null) {
          _eventInfoHourlySteps.value =
              eventInfoList.map((item) => (item['value'] ?? 0) as int).toList();
          developer.log('✅ 活动信息数据解析成功，共${_eventInfoHourlySteps.length}个时段',
              name: _tag);
        }
      }
    } catch (e) {
      developer.log('❌ 获取活动信息失败: $e', name: _tag);
    }
  }

  /// 获取锻炼记录
  Future<void> _fetchEventExerciseInfo(
      String deviceSn, String recordDate) async {
    try {
      final response = await DefaultApi().queryEventExerciseInfoGet(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: _getTypeFromTimeRange(),
        isShowErrMsg: false,
        isShowLoading: false,
      );
      developer.log('✅ 锻炼记录获取成功: $response', name: _tag);
    } catch (e) {
      developer.log('❌ 获取锻炼记录失败: $e', name: _tag);
    }
  }

  /// 获取对比走的距离
  Future<void> _fetchCompareDistanceRate(
      String deviceSn, String recordDate) async {
    try {
      final response = await DefaultApi().queryCompareDistanceRateGet(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: _getTypeFromTimeRange(),
        isShowErrMsg: false,
        isShowLoading: false,
      );
      developer.log('✅ 对比走的距离获取成功: $response', name: _tag);

      // 解析数据
      if (response != null && response['data'] != null) {
        _compareDistanceData.value =
            CompareDistanceData.fromJson(response['data']);
        developer.log('✅ 对比走的距离数据解析成功', name: _tag);
      }
    } catch (e) {
      developer.log('❌ 获取对比走的距离失败: $e', name: _tag);
    }
  }

  /// 获取过去七天达成目标情况
  Future<void> _fetchTargetSituation(String deviceSn, String recordDate) async {
    try {
      final response = await DefaultApi().queryTargetSituationGet(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: _getTypeFromTimeRange(),
        isShowErrMsg: false,
        isShowLoading: false,
      );
      developer.log('✅ 过去七天达成目标情况获取成功: $response', name: _tag);

      // 解析数据
      if (response != null && response['data'] != null) {
        final List<dynamic> dataList = response['data'];
        _targetSituationData.value =
            dataList.map((item) => DailyTargetData.fromJson(item)).toList();
        developer.log('✅ 过去七天达成目标数据解析成功，共${_targetSituationData.length}条',
            name: _tag);
      }
    } catch (e) {
      developer.log('❌ 获取过去七天达成目标情况失败: $e', name: _tag);
    }
  }

  /// 获取体力活动量
  Future<void> _fetchPhysicalActivityLevel(
      String deviceSn, String recordDate) async {
    try {
      final response = await DefaultApi().queryPhysicalActivityLevelGet(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: _getTypeFromTimeRange(),
        isShowErrMsg: false,
        isShowLoading: false,
      );
      developer.log('✅ 体力活动量获取成功: $response', name: _tag);
    } catch (e) {
      developer.log('❌ 获取体力活动量失败: $e', name: _tag);
    }
  }

  /// 获取选中日期的数据
  Future<void> fetchDataForSelectedDay(int index, bool isToday) async {
    setSelectedDayIndex(index);
    developer.log('📅 选中第 $index 天的数据', name: _tag);

    // 如果 API 数据已经存在，直接使用，不需要再次获取
    if (_targetSituationData.isNotEmpty &&
        index < _targetSituationData.length) {
      final selectedData = _targetSituationData[index];
      developer.log(
          '✅ 使用 API 数据: ${selectedData.dailyValue}, 步数: ${selectedData.steps}, 卡路里: ${selectedData.calorie}, 时长: ${selectedData.duration}分钟',
          name: _tag);
      return;
    }

    // 如果没有 API 数据，尝试从设备获取历史数据
    if (!isToday) {
      await _ringService.fetchStepsDataForDate(index);
    }
  }

  /// 处理柱状图拖动
  void handleChartPanUpdate(
      double localX, double barWidth, int chartDataLength) {
    if (currentTimeRange == TimeRange.day) {
      final barIndex =
          (localX / barWidth).floor().clamp(0, chartDataLength - 1);
      setSelectedTimeIndex(barIndex);
      setDragLineX(localX);
    }
  }

  /// 处理柱状图拖动结束
  void handleChartPanEnd() {
    setDragLineX(null);
  }

  /// 处理柱状图点击
  void handleChartTapUp(double localX, double barWidth, int chartDataLength) {
    if (currentTimeRange == TimeRange.day) {
      final barIndex =
          (localX / barWidth).floor().clamp(0, chartDataLength - 1);
      final newIndex = selectedTimeIndex == barIndex ? -1 : barIndex;
      setSelectedTimeIndex(newIndex);
    }
  }

  /// 显示错误消息
  void _showError(String message) {
    Toast.show(message);
  }

  /// 显示日历选择器
  Future<void> showCalendarPicker() async {
    // 导航到日历页面
    final result = await Get.toNamed('/activity_calendar');
    
    // 如果选择了日期，重新获取数据
    if (result != null && result is String) {
      developer.log('📅 从日历选择了日期: $result', name: _tag);
      await _fetchActivityDataForDate(result);
    }
  }

  /// 获取指定日期的活动数据
  Future<void> _fetchActivityDataForDate(String selectedDate) async {
    try {
      developer.log('📊 开始获取指定日期的活动数据: $selectedDate', name: _tag);

      // 获取设备SN
      final deviceSnManager = Get.find<DeviceSnManager>();
      final deviceSn = deviceSnManager.getDeviceSn();
      
      if (deviceSn.isEmpty) {
        developer.log('⚠️ 设备SN为空，无法获取活动数据', name: _tag);
        return;
      }

      // 并行调用所有接口
      await Future.wait([
        _fetchEventInfo(deviceSn, selectedDate),
        _fetchEventExerciseInfo(deviceSn, selectedDate),
        _fetchCompareDistanceRate(deviceSn, selectedDate),
        _fetchTargetSituation(deviceSn, selectedDate),
        _fetchPhysicalActivityLevel(deviceSn, selectedDate),
      ]);

      developer.log('✅ 指定日期的活动数据获取完成', name: _tag);
    } catch (e) {
      developer.log('❌ 获取指定日期的活动数据异常: $e', name: _tag);
    }
  }
}
